{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import re\n",
    "from pyvis.network import Network\n",
    "from  pyltp import Segmentor, Postagger, Parser, SementicRoleLabeller"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def parser_main(sentence):\n",
    "    LTP_DIR=\"./ltp_data_v3.4.0\"\n",
    "    segmentor=Segmentor(os.path.join(LTP_DIR,\"cws.model\"))\n",
    "    postagger=Postagger(os.path.join(LTP_DIR,\"pos.model\"))\n",
    "    parser=Parser(os.path.join(LTP_DIR,\"parser.model\"))\n",
    "    labeller=SementicRoleLabeller(os.path.join(LTP_DIR,\"pisrl_win.model\"))\n",
    "    wods=list(segmentor.segment(sentence))\n",
    "    arcs=parser.parse(words,postags)\n",
    "    roles=labeller.label(words,postags,arcs)\n",
    "    roles_dict={key:{sub_key:[sub_key,8value] for sub_key,value in sub_data}for key,sub_data in roles}\n",
    "    return words,postags,arcs,roles_dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "text=\"苏轼是宋朝的著名文学家，黄庭坚是苏轼的好朋友。苏轼擅长写词，而黄庭坚擅长写诗。黄庭坚游览黄州，并赞叹黄山之美。黄庭坚探望苏轼，并一起吟诗作对。\"\n",
    "words,postags,arcs,roles_dict=parser_main(text)\n",
    "print(\"分词结果:\",words)\n",
    "print(\"语义角色标注结果:\",roles_dict)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def ruler(words,postags,roles_dict,role_index):\n",
    "    v=words[role_index]\n",
    "    role_info=roles_dict[role_index]\n",
    "    if 'A0'in role_info.keys()and 'A1'in role_info.keys():\n",
    "        s=''.join([words[word_index]for word_index in range(role_info['A0'][1], role_info['A0'][2]+1) if postags[word_index][0]not in['w','u','x']and words[word_index]])\n",
    "        o=''.join([words[word_index]for word_index in range(role_info['A1'][1], role_info['A1'][2]+1) if postags[word_index][0]not in['w','u','x']and words[word_index]])\n",
    "        if s and o:\n",
    "            return'1',[s,v,o]\n",
    "        return '4',[]"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
